/** 新建因子 POST /api/addFactor */
export async function addstudent(options?: { [key: string]: any }) {
  const token = localStorage.getItem("token")
  return fetch("/api/student", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
      authorization:"Bearer " + token
    },
    body: JSON.stringify(options)
  }).then(res => res.json()).then(res=>{
    if(res.statusCode){
      if(res.statusCode<300 && res.statusCode>=200){
        return {
          success: true
        }
      }else{
        throw new Error(res.message)
      }
    }
    return {
      success: true,
      data:res
    }
  })
}

export async function student(options: any): Promise<{
  success: boolean;
  data: any[];
}> {
  const urlObj = new URL("http://localhost:3000/api/student")
  Object.keys(options).forEach((item:string)=>{
    urlObj.searchParams.set(item,options[item])
  })
  return fetch(urlObj.href.replace("http://localhost:3000/","")).then(res => res.json()).then(studentList => {
    return {
      success: true,
      data: studentList,
    }
  })
}

export async function updatestudent(options?: { [key: string]: any }) {
  const token = localStorage.getItem("token")
  return fetch("/api/student/" + options!.StuId, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      authorization:"Bearer " + token
    },
    body: JSON.stringify(options)
  }).then(res=>res.json()).then(res=>{
    if(res.statusCode){
      if(res.statusCode<300 && res.statusCode>=200){
        return {
          success: true
        }
      }else{
        throw new Error(res.message)
      }
    }
    return {
      success: true,
      data:res
    }
  })
}


/** 删除因子 POST /api/deleteFactor
 * 这个地方说是删除，实际上是将整个 factor 的 isvalid 给变为false
 */
export async function deletestudent(options?: { [key: string]: any }) {
  const token = localStorage.getItem("token")
  console.log("options : ",options)
  return fetch("/api/student/" + options!.StuId, {
    method: "DELETE",
    headers: {
      'Content-Type': 'application/json',
      authorization:"Bearer " + token
    }
  }).then(res => res.json()).then((res) => {
    if(res.statusCode){
      if(res.statusCode<300 && res.statusCode>=200){
        return {
          success: true
        }
      }else{
        throw new Error(res.message)
      }
    }
    return {
      success: true,
      data:res
    }
    
  })
}
